package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jiedan/student-web/server/model"
	"github.com/jiedan/student-web/server/service"
	"gorm.io/gorm"
)

// TeacherHandler 教师处理器
type TeacherHandler struct {
	DB *gorm.DB
}

// NewTeacherHandler 创建教师处理器
func NewTeacherHandler(db *gorm.DB) *TeacherHandler {
	return &TeacherHandler{DB: db}
}

// GetTeachers 获取所有教师
func (h *TeacherHandler) GetTeachers(c *gin.Context) {
	var teachers []model.Teacher
	result := h.DB.Preload("User").Preload("User.Role").Find(&teachers)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get teachers"})
		return
	}

	c.JSON(http.StatusOK, teachers)
}

// GetTeacher 获取单个教师
func (h *TeacherHandler) GetTeacher(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid teacher ID"})
		return
	}

	var teacher model.Teacher
	result := h.DB.Preload("User").Preload("User.Role").First(&teacher, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Teacher not found"})
		return
	}

	c.JSON(http.StatusOK, teacher)
}

// CreateTeacherRequest 创建教师请求
type CreateTeacherRequest struct {
	UserID      uint   `json:"user_id" binding:"required"`
	Department  string `json:"department"`
	Title       string `json:"title"`
	Description string `json:"description"`
}

// CreateTeacher 创建教师
func (h *TeacherHandler) CreateTeacher(c *gin.Context) {
	var req CreateTeacherRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
		return
	}

	// 创建教师服务
	teacherService := service.NewTeacherService(h.DB)

	// 创建教师记录
	teacher, err := teacherService.CreateTeacher(req.UserID, req.Department, req.Title, req.Description)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "Teacher created successfully", "teacher": teacher})
}

// UpdateTeacherRequest 更新教师请求
type UpdateTeacherRequest struct {
	Department  string `json:"department"`
	Title       string `json:"title"`
	Description string `json:"description"`
}

// UpdateTeacher 更新教师
func (h *TeacherHandler) UpdateTeacher(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid teacher ID"})
		return
	}

	var req UpdateTeacherRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
		return
	}

	// 查找教师
	var teacher model.Teacher
	result := h.DB.First(&teacher, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Teacher not found"})
		return
	}

	// 更新教师信息
	if req.Department != "" {
		teacher.Department = req.Department
	}
	if req.Title != "" {
		teacher.Title = req.Title
	}
	if req.Description != "" {
		teacher.Description = req.Description
	}

	// 保存更新
	result = h.DB.Save(&teacher)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update teacher"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Teacher updated successfully"})
}

// DeleteTeacher 删除教师
func (h *TeacherHandler) DeleteTeacher(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid teacher ID"})
		return
	}

	// 查找教师
	var teacher model.Teacher
	result := h.DB.First(&teacher, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Teacher not found"})
		return
	}

	// 检查教师是否有关联的课程
	var courseCount int64
	h.DB.Model(&model.Course{}).Where("teacher_id = ?", id).Count(&courseCount)
	if courseCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Cannot delete teacher with associated courses"})
		return
	}

	// 删除教师记录
	result = h.DB.Delete(&teacher)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete teacher"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Teacher deleted successfully"})
}